package io.shallwe.scanner.log;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import io.shallwe.common.model.Scanner;
import io.shallwe.common.model.ScannerRecord;

/**
 * @date 2019-11-11
 */
public class ScannerRecordService {

    public static final  String CACHE_NAME = "scanner-record";

    public static final String AUTO_SCAN_ENTER ="AUTO_SCAN_ENTER";

    public static final String AUTO_SCAN_EXIT ="AUTO_SCAN_EXIT";

    public static final String AUTO_SCAN ="AUTO_SCAN";

    private ScannerRecord scannerRecordDao = new ScannerRecord().dao();

    /**
     * 查找最近的上线条码记录
     * @return
     */
    public ScannerRecord getLastOnlineAutoScanRecord(){
        ScannerRecord record = CacheKit.get(ScannerRecordService.CACHE_NAME,ScannerRecordService.AUTO_SCAN_ENTER);
        if(record==null){
            record = scannerRecordDao.template("log.getLastOnlineAutoScanRecord").findFirst();
            CacheKit.put(ScannerRecordService.CACHE_NAME,ScannerRecordService.AUTO_SCAN_ENTER,record);
        }
        return record;
    }


    /**
     * 查找最近的上线条码记录
     * @return
     */
    public ScannerRecord getLastOfflineAutoScanRecord(){
        ScannerRecord record = CacheKit.get(ScannerRecordService.CACHE_NAME,ScannerRecordService.AUTO_SCAN_EXIT);
        if(record==null){
            record = scannerRecordDao.template("log.getLastOfflineAutoScanRecord").findFirst();
            CacheKit.put(ScannerRecordService.CACHE_NAME,ScannerRecordService.AUTO_SCAN_ENTER,record);
        }
        return record;
    }



    /**
     * 清除系统历史扫描数据
     */
    public void clearHistoryData(){
        Db.template("log.clearHistoryData").update();
        CacheKit.removeAll(ScannerRecordService.CACHE_NAME);
    }

    /**
     *查询最早的自动扫描记录
     * @return
     */
    public ScannerRecord getHeadScannerRecord(){
        ScannerRecord record =  scannerRecordDao.template("log.getHeadScannerRecord").findFirst();
        return record;
    }

    public void updateRecord(ScannerRecord record){
        record.update();
        CacheKit.removeAll(ScannerRecordService.CACHE_NAME);
    }
}
